<?php
namespace App\Pull;


use App\Librarys\Curl;
use App\Librarys\Mylog;

class Base
{
    /**
     * 发起请求
     * @param stirng $method "curl方法"， string $url "curl url", array $data "curl参数", int $expire "缓存时间，0不缓存"
     * @return $err, $res
     */
    protected  function call($method, $url, array $data = null, $expire = 0)
    {
        //todo 调用外部api加入redis，后续用。
        list($err, $res) = Curl::$method($url, $data);
        // 记录日志
        $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
        $logfile = strtolower(str_replace('\\', '_', $trace[1]['class'])) . '_' . strtolower($trace[1]['function']);
        MyLog::info($logfile, ['url' => $url, 'method' => $method, 'req' => $data, 'res' => $res, ]);
        if ($err) {
            return null;
        }
        list($err, $res) = $this->parse($res);
        return [$err, $res];
    }

    /**
     * 返回值解析
     * @return $err, $res
     */
    protected function parse($res)
    {
        $res = json_decode($res, true);
        if (!isset($res['err_code'])) {
            return [1, $res];
        }
        if ($res['err_code'] !=0) {
            return [1, $res];
        }
        return [0, $res['data']];
    }
}

